package com.suzhe.ymall.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhe.ymall.common.annotation.ExcludeAuth;
import com.suzhe.ymall.common.annotation.LoginAuth;
import com.suzhe.ymall.common.utils.IdWorker;
import com.suzhe.ymall.common.utils.LoginUserUtils;
import com.suzhe.ymall.common.utils.YMJsonUtils;
import com.suzhe.ymall.order.vo.OrderVo;
import com.suzhe.ymall.pay.client.OrderClient;
import com.suzhe.ymall.pay.config.AlipayConfig;
import com.suzhe.ymall.pay.enums.PayStatusEnum;
import com.suzhe.ymall.pay.pojo.PayRecord;
import com.suzhe.ymall.pay.service.IPayRecordService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/pay")
@Slf4j
public class PayController {

    @Autowired
    IPayRecordService iPayRecordService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    OrderClient orderClient;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @Value("${ym.payResultUrl}")
    private String payResultUrl;

    @Autowired
    AlipayConfig alipayConfig;


    @GetMapping("/goPay")
    @LoginAuth
    @ResponseBody
    public void  goPay(String orderNo,Integer payPlatform,HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(),//
                alipayConfig.getAppId(), alipayConfig.getMerchantPrivateKey(), "json",//
                alipayConfig.getCharset(), alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType());

        //设置请求参数
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest ();
        OrderVo orderVo = orderClient.getOrderVoByOrderNo(orderNo);
        Long actualPay = orderVo.getActualPay();
        BigDecimal totalAmount = new BigDecimal(actualPay).divide(new BigDecimal("100"));
        Integer userId = LoginUserUtils.getAppLoginUser().getId();
        PayRecord  payRecord = iPayRecordService.getOne(new QueryWrapper<PayRecord>().eq("order_no", orderNo));
        if (payRecord == null){
            payRecord = new PayRecord();
            payRecord.setPayNo(idWorker.nextId());
            payRecord.setOrderNo(orderNo);
            payRecord.setPayPlatform(payPlatform);
            payRecord.setUserId(userId);
            payRecord.setPayPlatform(1);
            payRecord.setPayAmount(actualPay);
            payRecord.setStatus(PayStatusEnum.WAIT_BUYER_PAY.value());
            iPayRecordService.save(payRecord);
        }

        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());

        Map<String,Object> bizParams = new HashMap<String,Object>();
        bizParams.put("out_trade_no",payRecord.getPayNo());
        bizParams.put("total_amount",totalAmount);
        bizParams.put("product_code","QUICK_WAP_WAY");
        bizParams.put("subject",payRecord.getPayNo());
        alipayRequest.setBizContent(YMJsonUtils.toJson(bizParams));//填充业务参数
        log.info("goAlipay:{}", alipayRequest.getBizContent());
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + alipayConfig.getCharset());
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/notifyUrl")
    @ExcludeAuth
    @ResponseBody
    public String notifyUrl(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        log.debug("接受支付返回的通知");
        // 编码
        String charset = alipayConfig.getCharset();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        log.info("notifyUrl params:{}",params);

        boolean validation = false;
        String result = "false";
        try {
            validation = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), charset,
                    alipayConfig.getSignType());

            if (validation) {
                //TODO 根据业务需要进行处理
                String outTradeNo = params.get("out_trade_no").trim();
                String tradeNo = params.get("trade_no").trim();
                Long payNo = Long.parseLong(outTradeNo);
                PayRecord payRecord = iPayRecordService.getById(payNo);
                payRecord.setTradeNo(tradeNo);
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus)){
                    payRecord.setStatus(PayStatusEnum.TRADE_SUCCESS.value());
                }else{
                    payRecord.setStatus(PayStatusEnum.TRADE_FAILURE.value());
                }
                boolean update = iPayRecordService.updateById(payRecord);
                if ("TRADE_SUCCESS".equals(tradeStatus) && update){
                    //向消息队列发送订单状态的消息
                    iPayRecordService.sendPaySuccess(payRecord);
                }

                result = "success";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;

    }


    @GetMapping("/returnUrl")
    @ExcludeAuth
    public void returnUrl(HttpServletRequest request,HttpServletResponse response) throws IOException {
        // 编码
        String charset = alipayConfig.getCharset();
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        log.info("returnUrl params:{}", params);
        boolean validation = false;
        String orderNo = null;
        try {
            validation = AlipaySignature.rsaCheckV1(params, alipayConfig.getAlipayPublicKey(), charset,
                    alipayConfig.getSignType());
            if (validation) {
                String outTradeNo = params.get("out_trade_no").trim();
                String tradeNo = params.get("trade_no").trim();
                Long payNo = Long.parseLong(outTradeNo);
                PayRecord payRecord = iPayRecordService.getById(payNo);
                orderNo = payRecord.getOrderNo();
                log.info("验证通过");
            }else{
                log.info("验证失败");
            }
        } catch (AlipayApiException e) {
            log.error("returnUrl 异常",e);
        }
        //TODO 根据业务需要进行处理
        response.sendRedirect(String.format(payResultUrl,orderNo));

    }


}
